package com.ca.singlesignon.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**
 * Create By Gary
 */
@Configuration
public class RedisShardedPool {

    @Value("${spring.redis.host}")
    private   String ip;

    @Value("${spring.redis.password}")
    private   String password;

    @Value("${spring.redis.port}")
    private   Integer port;

    @Value("${spring.redis.port2}")
    private   Integer port2;

    @Value("${spring.redis.database}")
    private Integer database;

    @Value("${spring.redis.jedis.pool.max-active}")
    private  Integer maxTotal;//最大连接数

    @Value("${spring.redis.jedis.pool.max-idle}")
    private  Integer maxIdle; //最大空闲实例个数

    @Value("${spring.redis.jedis.pool.min-idle}")
    private  Integer minIdle; //最小空闲实例个数

    private  Boolean testOnBorrow=true;//true 表示得到的实例可用

    private  Boolean testOnReturn=true;//true 表示归还的实例可用

    @Bean(name = "shardedJedisPool")
    public  ShardedJedisPool shardedJedisPool(){

        JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setBlockWhenExhausted(true);  //连接耗尽时是否阻塞，true阻塞直到超时
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestOnBorrow(testOnReturn);

        JedisShardInfo info=new JedisShardInfo(ip,port,1000*2);
        info.setPassword(password);
        JedisShardInfo info2=new JedisShardInfo(ip,port2,1000*2);
        info2.setPassword(password);
        List<JedisShardInfo> shardInfoList=new ArrayList<>(2);
        shardInfoList.add(info);
        shardInfoList.add(info2);
        return new ShardedJedisPool(jedisPoolConfig,shardInfoList,Hashing.MURMUR_HASH,Sharded.DEFAULT_KEY_TAG_PATTERN);
    }

    public  ShardedJedis getJedis(){
        return shardedJedisPool().getResource();
    }

    public  void returnBrokenResource(ShardedJedis jedis){
        shardedJedisPool().returnBrokenResource(jedis);
    }

    public  void returnResource(ShardedJedis jedis){
        shardedJedisPool().returnResource(jedis);
    }

}
